import XLSX from './xlsx.bundle.js';
const s2ab = str => {
  const buf = new ArrayBuffer(str.length);
  const view = new Uint8Array(buf);
  for (let i = 0; i !== str.length; ++i) view[i] = str.charCodeAt(i) & 0xff;
  return buf;
};
export const JsonToFileData = ({ worksheet, data, ownerInstance }) => {
  const workbook = XLSX.utils.book_new();
  XLSX.utils.book_append_sheet(workbook, worksheet, 'Sheet1'); // sheet1 是自定义的sheet名
  // XLSX.write 会根据type返回值，为什么选择binary类型，因为binary好歹是个string，H5+的io写入api只支持写入string类型的
  let binaryData = XLSX.write(workbook, { bookType: 'xlsx', bookSST: false, type: 'binary' });
  let blobData = new Blob([s2ab(binaryData)], { type: 'application/octer-stream' });
  let reader = new FileReader();
  reader.readAsDataURL(blobData);
  reader.onload = evt => {
    let base64Data = evt.target.result.replace(/^data:\S+\/\S+;base64,/, '');
    // #ifdef APP-PLUS
    // 将 ownerInstance 挂载到that上，否则写入完成后，无法通过ownerInstance调用逻辑层的方法 ！！
    exportFile(base64Data, ownerInstance, data.name);
    // #endif
  };
};
// 导出文件到手机 fileData:要写入到文件的数据，返回参数为文档路径
export const exportFile = (fileData, ownerInstance, name = '订单') => {
  plus.io.requestFileSystem(plus.io.PUBLIC_DOCUMENTS, fs => {
    let fullPath = fs.root.fullPath;
    // 创建文件夹
    fs.root.getDirectory(name, { create: true }, dirEntry => {
      //获取当前的年月继续创建文件夹
      let date = new Date();
      let year = date.getFullYear();
      let month = date.getMonth() + 1;
      dirEntry.getDirectory(`${year}年${month}月`, { create: true }, dirEntry2 => {
        // 创建文件,防止重名
        // ------------------------开始时间------------------------
        const d = new Date();
        let startTime = `${d.getFullYear()}年${d.getMonth() + 1}月${d.getDate()}日 ${d.getHours()}时${d.getMinutes()}分${d.getSeconds()}秒`;
        let fileName = `${name}${startTime}`;
        dirEntry2.getFile(`${fileName}.xlsx`, { create: true }, fileEntry => {
          fileEntry.createWriter(
            writer => {
              //  /storage/emulated/0指的就是系统路径
              let filePath = fullPath.replace('/storage/emulated/0', '');
              writer.onwrite = e => {
                ownerInstance.callMethod('writeOver', { filePath, name, date: `${year}年${month}月`, fileName: `${fileName}.xlsx` });
              };
              // 写入内容;
              writer.writeAsBinary(fileData);
            },
            err => {
              console.log(err);
            }
          );
        });
      });
    });
  });
};
